package com.wj.service;

import com.wj.remote.ServiceVerificationCodeClient;
import com.wj.responese.ResultResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class VerificationCodeService {

    public static final int VERIFICATION_CODE_LENGTH = 6;
    public static final int VERIFICATION_CODE_EXPIRATION = 2; // 验证码过期时间（分钟）
    public static final String PREFIX = "api-passenger-verificationCode-";

    @Autowired
    ServiceVerificationCodeClient serviceVerificationCodeClient;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public ResultResponse<String> sendVerificationCode(String passengerPhone) {
        ResultResponse<String> resultResponse = serviceVerificationCodeClient.numberCode(VERIFICATION_CODE_LENGTH);
        if (resultResponse.getCode() != 200){
            return resultResponse;
        }
        String verificationCode = resultResponse.getData();
        try {
            //TODO 日志记录redis调用
            stringRedisTemplate.opsForValue().set(PREFIX + passengerPhone, verificationCode, VERIFICATION_CODE_EXPIRATION, TimeUnit.MINUTES);
        } catch (Exception e) {
            //TODO 日志记录异常状态
            System.err.println("Failed to set verification code in Redis: " + e.getMessage());
            return ResultResponse.failure("Internal server error");
        }
        return sendSms(passengerPhone, verificationCode);
    }

    private ResultResponse<String> sendSms(String phoneNumber, String verificationCode) {
        try {
            // 模拟短信发送，实际开发中应替换为真实调用
            System.out.println("send" + verificationCode + " code to " + phoneNumber);
        } catch (Exception e) {
            // 添加异常处理逻辑，记录日志或执行其他恢复措施
            System.err.println("Failed to send verification code via SMS: " + e.getMessage());
            return ResultResponse.failure("Failed to send SMS");
        }
        return ResultResponse.success();
    }

}
